package com.nineclock.system.service.impl;

import afu.org.checkerframework.checker.units.qual.A;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.system.dto.SysRegisterDTO;
import com.nineclock.system.mapper.SysUserMapper;
import com.nineclock.system.pojo.SysUser;
import com.nineclock.system.service.SMSService;
import com.nineclock.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class SysUserServiceImpl implements SysUserService {


    @Autowired
    private SMSService smsService;

    @Autowired
    private SysUserMapper userMapper;
    //用户注册
    @Override
    public Long register(SysRegisterDTO sysRegisterDTO) {


        //健壮性判断
        if(sysRegisterDTO == null
                || sysRegisterDTO.getMobile() == null
                || sysRegisterDTO.getPassword() == null
                || sysRegisterDTO.getCheckcode() == null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        //验证码对比
        String newMobile = sysRegisterDTO.getMobile();
        String newCheckcode = sysRegisterDTO.getCheckcode();

        Boolean verifyCode = smsService.verifyCode(newCheckcode, newMobile, SMSConstant.SMS_TYPE_REGISTER);
            if (!verifyCode){
                throw new NcException(ResponseEnum.CODE_IMAGE_ERROR);
            }

            //保存用户对密码进行加密
            SysUser newUser = new SysUser();
            newUser.setMobile(newMobile);
            newUser.setPassword(new BCryptPasswordEncoder().encode(sysRegisterDTO.getPassword()));
            newUser.setStatus((short) 1);
            newUser.setCreateTime(new Date());
            userMapper.insert(newUser);

         //删除Redis内的验证码
        smsService.deleteSmsCode(newMobile,SMSConstant.SMS_TYPE_REGISTER);

        return newUser.getId();
    }
}
